// packageC/pages/comment/comment.js
import { timestampToTime } from '../../../utils/getNowTime';
import { getUserInfo } from '../../../utils/userInfo';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Notify from '../../../miniprogram_npm/@vant/weapp/notify/notify';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        talkDetail: Object, // 该话题的详情信息
        nowTime: '', // 现在的时间
        showIpt: false, // 显示输入框
        uploadImgUrl: '', // 回复的图片
        iptVal: '', // 输入框的值
        tid: '',
        point: '', // 锚点值
        screenHeight: 0, // 屏幕上升多高
        commentTopFixed: false, // 控制评论标签是否定位
        empty: false,
        myselfUid: getUserInfo()._id,
    },

    //控制回到顶部按钮的显示与消失
    scrollTopFun(e) {
        const that = this;
        e.detail.scrollTop;
        // console.log(e.detail.scrollTop);
        //创建节点选择器
        var query = wx.createSelectorQuery();
        //选择id
        query.select('#detail').boundingClientRect((rect) => {
            // console.log(rect);
            // console.log(rect.height, e.detail.scrollTop);
            if (rect.height + 25 <= e.detail.scrollTop) {
                that.setData({
                    commentTopFixed: true,
                });
            } else {
                that.setData({
                    commentTopFixed: false,
                });
            }
        }).exec();
    },

    // 点击头像，跳转到用户发布的信息页
    toUserDiscussDetail(e) {
        const { uid, avatar, nickname } = e.currentTarget.dataset;
        wx.navigateTo({
            url: `../../../pages/userDiscussDetail/userDiscussDetail?uid=${uid}&avatar=${avatar}&nickname=${nickname}`,
        })
    },

    // 显示输入框
    onComment() {
        this.setData({
            showIpt: true,
        })
    },

    // 关闭输入框
    closeCommentIpt() {
        this.setData({
            showIpt: false,
        })
    },

    // 选择图片
    afterRead(e) {
        this.setData({
            uploadImgUrl: e.detail.file.url,
        })
    },

    // 删除预上传的评论图片
    delUploadImgUrl() {
        this.setData({
            uploadImgUrl: '',
        })
    },

    // 输入框的值
    onChangeIptVal(e) {
        this.setData({
            iptVal: e.detail.value,
        });
    },

    // 上传评论
    onSend() {
        if (getUserInfo()) {
            const that = this;
            const { iptVal, uploadImgUrl, tid } = that.data;
            const { nickname, avatar, _id } = getUserInfo();
            console.log(iptVal, uploadImgUrl, nickname, avatar, _id);
            if (iptVal === '') {
                wx.showToast({
                    title: '你要先输入评论才能发送',
                    icon: 'none',
                })
            } else {
                // 没有评论图片，不需要传入云存储，只上传评论
                if (uploadImgUrl === '') {
                    wx.cloud.callFunction({
                        name: 'reqTalkAPI',
                        data: {
                            scene: 'ADD_ONE_COMMENT',
                            tid,
                            commentVal: iptVal,
                            commentImgUrl: uploadImgUrl, // 这里是空的，但也要传进去云函数
                            uid: _id,
                            nickname,
                            avatar,
                        }
                    }).then(res => {
                        const { updated } = res.result.stats;
                        if (updated === 1) {
                            wx.showToast({
                                title: '评论成功',
                                success: () => {
                                    this.getTalkDetail(tid);
                                    this.setData({
                                        showIpt: false,
                                    })
                                },
                            })
                        }
                    })
                } else {
                    wx.cloud.uploadFile({
                        cloudPath: `${Math.random()}-${Math.ceil(Math.random() * 1000)}-${tid}.png`,
                        filePath: uploadImgUrl, // 文件路径
                    }).then(res => {
                        // get resource ID
                        console.log(res.fileID)
                        wx.cloud.callFunction({
                            name: 'reqTalkAPI',
                            data: {
                                scene: 'ADD_ONE_COMMENT',
                                tid,
                                commentVal: iptVal,
                                commentImgUrl: res.fileID,
                                uid: _id,
                                nickname,
                                avatar,
                            }
                        }).then(res2 => {
                            console.log(res2.result.stats);
                            const { updated } = res2.result.stats;
                            if (updated === 1) {
                                wx.showToast({
                                    title: '评论成功',
                                    success: () => {
                                        this.getTalkDetail(tid);
                                        this.setData({
                                            showIpt: false,
                                        })
                                    },
                                })
                            }
                        })
                    }).catch(error => {
                        // handle error
                        wx.showToast({
                            title: '评论失败',
                            icon: 'none',
                        })
                    })
                }
            }
        } else {
            Notify({ type: 'danger', message: '请先登录' });
        };
    },

    /**
     * 点击图片进行预览
     */
    onPreviewImg: function (event) {
        var src = event.currentTarget.dataset.src;//获取data-src
        var imgList = event.currentTarget.dataset.list;//获取data-list
        //图片预览
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: imgList // 需要预览的图片http链接列表
        })
    },

    /**
    * 点击单个图片进行预览
    */
    onPreviewOneImg: function (event) {
        var src = event.currentTarget.dataset.src;//获取data-src
        const urls = [src];
        //图片预览
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls,
        })
    },


    // 获取此讨论的详情信息
    getTalkDetail(tid) {
        // 根据tid，获取该讨论的详情信息
        wx.cloud.callFunction({
            name: 'reqTalkAPI',
            data: {
                scene: 'GET_ONE_TALK_DETAIL',
                tid,
            }
        }).then(res => {
            console.log(res.result.data);
            const { creatDate } = res.result.data;
            this.setData({
                talkDetail: res.result.data,
                nowTime: timestampToTime(creatDate),
            }, () => {
                if (res.result.data.commentArr.length === 0) {
                    // 评论为0时，显示空页面
                    this.setData({
                        empty: true,
                    });
                }
            })
        })
    },

    // 点赞和取消点赞
    onClickLike(e) {
        if (getUserInfo()) {
            const that = this;
            // 首先要判断，是点赞还是取消点赞
            const { islike, tid } = e.currentTarget.dataset;
            const uid = getUserInfo()._id;
            const { talkDetail } = that.data;
            if (!islike) {
                // 说明要进行点赞操作
                wx.cloud.callFunction({
                    name: 'reqTalkAPI',
                    data: {
                        scene: 'DEFINE_LIKE',
                        tid,
                        uid,
                    }
                }).then(res => {
                    console.log(res);
                    const { update1, update2 } = res.result;
                    if (update1.stats.updated === 1 && update2.stats.updated === 1) {
                        Toast.success('点赞成功');
                        // 点赞成功，要实现页面上实时刷新
                        let newTalkDetail = talkDetail;
                        newTalkDetail.likeArr.push(uid);
                        that.setData({
                            talkDetail: { ...newTalkDetail },
                        });
                    } else {
                        Toast.fail('点赞失败');
                    }
                })
            } else {
                // 说明要进行取消点赞
                wx.cloud.callFunction({
                    name: 'reqTalkAPI',
                    data: {
                        scene: 'CANCEL_LIKE',
                        tid,
                        uid,
                    }
                }).then(res => {
                    console.log(res);
                    const { update1, update2 } = res.result;
                    if (update1.stats.updated === 1 && update2.stats.updated === 1) {
                        Toast.success('取消成功');
                        // 取消成功，要实现页面上实时刷新
                        let newTalkDetail = talkDetail
                        newTalkDetail.likeArr.forEach((item, index) => {
                            if (item === uid) {
                                newTalkDetail.likeArr.splice(index, 1);
                            };
                        });
                        that.setData({
                            talkDetail: { ...newTalkDetail },
                        });
                    } else {
                        Toast.fail('取消失败');
                    }
                })
            }
        } else {
            Notify({ type: 'danger', message: '请先登录' });
        };
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options);
        const { tid, nickname, point } = options;
        // 设置导航栏的标题
        wx.setNavigationBarTitle({
            title: nickname
        });
        this.getTalkDetail(tid);
        setTimeout(() => {
            this.setData({
                tid,
                point,
                screenHeight: wx.getSystemInfoSync().windowHeight, // 获取屏幕高度
            })
        }, 500)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})